#ifndef __M_SOCKET_H__
#define __M_SOCKET_H__

#include <sys/types.h>          
#include <sys/socket.h>
#include "InetAddr.hpp"

// 封装tcp套接字相关的函数，比如创建套接字socket、绑定端口bind、设置监听listen、等待连接accpet、发起连接connect
// 主要提供静态方法

class SocketMethod {
    public:
        static int SocketCreate() {
            int sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if(sockfd < 0) {
                std::cerr << "create socket error" << std::endl;
                exit(-1);
            }

            // 设置端口复用
            int opt = 1;
            setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
            return sockfd;
        }

        static void SocketBind(int sockfd, int port) {
            InetAddr addr(port);
            socklen_t len = addr.NetAddrLen();
            if(bind(sockfd, addr.netAddrPtr(), len) < 0) {
                std::cerr << "bind error" << std::endl;
                exit(-1);
            }
        }

        static void SocketListen(int sockfd, int backlog) {
            if(listen(sockfd, backlog) < 0) {
                std::cerr << "listen error" << std::endl;
                exit(-1);
            }
        }

};

#endif